<template>
  <el-dialog
    :title="{ add: '新增部门', edit: '编辑部门' }[mode]"
    style="600px"
    :visible.sync="isSTop"
    @close="resetForm"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="form.name" placeholder="1-50个字符"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" placeholder="1-50个字符"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          placeholder="请选择负责人"
          @focus="getUserList"
        >
          <el-option
            v-for="item in ursrList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          placeholder="1-300个字符"
          type="textarea"
          :rows="4"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align:center">
        <el-button>取消</el-button>
        <el-button type="primary" @click="suost">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments'
export default {
  props: {
    initList: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      mode: '',
      isSTop: false,
      localItem: '',
      ursrList: [],
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 必填
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // const temp = this.initList.filter(item => {
              //   if (item.pid === this.localItem.id) {
              //     return true
              //   }
              // })
              // const bol = temp.some(item => {
              //   return item.name === value
              // })
              let temp
              if (this.mode === 'add') {
                temp = this.initList.filter(item => {
                  if (item.pid === this.localItem.id) {
                    return true
                  }
                })
              } else if (this.mode === 'edit') {
                // 1:找出点击项的兄弟项，且排除自己
                temp = this.initList.filter(item => {
                  return (
                    item.pid === this.localItem.pid &&
                    item.id !== this.localItem.id
                  )
                })
              }
              const bol = temp.some(item => {
                return item.name === value
              })
              bol
                ? callback(new Error('请不要输入同名部门:' + value))
                : callback()
            }
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // const bol = this.initList.every(item => {
              //   return item.code !== value
              // })
              //  编辑时表单验证处理，分场景处理:新增与编辑
              let bol = true
              if (this.mode === 'add') {
                bol = this.initList.every(item => {
                  return item.code !== value
                })
              } else if (this.mode === 'edit') {
                const tempAdd = this.initList.filter(item => {
                  return item.id !== this.localItem.id
                })
                bol = tempAdd.every(item => {
                  return item.code !== value
                })
              }
              bol ? callback() : callback(new Error('请不要输入相同名code'))
            }
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  //  兄弟组件传值 监听与销毁
  mounted () {
    this.$bus.$on('showAdd', (bol, item, mode) => {
      this.isSTop = bol
      this.localItem = item
      this.mode = mode
      if (mode === 'edit') {
        console.log(item)
        // 深拷贝
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  //  销毁
  beforeDestroy () {
    this.$bus.$off('showAdd')
  },
  methods: {
    async getUserList () {
      if (!this.ursrList.length) {
        const res = await sysUserSimple()
        this.ursrList = res.data.data
        console.log('获取员工数据', res)
      }
    },
    //  确定点击
    suost () {
      this.$refs.form.validate(async result => {
        if (result) {
          if (this.mode === 'add') {
            this.form.pid = this.localItem.id
            await companyDepartmentPost(this.form)
            // 新增成功提醒
            this.$message.success('新增成功')
          } else if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('编辑成功')
          }
          // 关闭弹窗
          this.isSTop = false
          //  刷新父级列表数据
          this.$emit('getData')
        }
      })
    },
    //  重置表单事件
    resetForm () {
      //  清空表单数据
      // 注意点:他会重置表单数据渲染时的值(第一次打开弹框时的form表单的值)
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    }
  }
}
</script>

<style></style>
